<?php

class IndexController extends Zend_Controller_Action
{
	private $_acl;
	
    public function init()
    {
    	$this->_helper->layout()->disableLayout();
		$this->view->base_url=BASE_URL;
		$this->base_dojo_folder='/dojotoolkit';
		
		    	
    	Zend_Dojo::enableView($this->view);
		$this->view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
		$this->view->dojo()
			->setLocalPath (PROTO.$_SERVER['HTTP_HOST'].$this->base_dojo_folder.'/dojo/dojo.js')
		    ->setDjConfig(array('parseOnLoad' => 'true', 'isDebug'=> 'false', 'locale'=>'es'));

		$this->view->headStyle()->appendStyle('
			@import "'.$this->base_dojo_folder.'/dijit/themes/claro/claro.css";
		');	
    }

    public function indexAction()
    {
        // action body
        if(!Zend_Auth::getInstance()->hasIdentity()) $this->_redirect('index/login');
        $userInfo = Zend_Auth::getInstance()->getStorage()->read();
        $this->_acl = new Zwei_Admin_Acl($userInfo->user_name);
		$this->view->user_name=$userInfo->user_name;
		$this->view->first_names=$userInfo->first_names;
		$this->view->last_names=$userInfo->last_names;
		$this->view->user_id=$userInfo->id;				
   	
        $this->view->dojo()
        	->requireModule("dijit.layout.BorderContainer")
			->requireModule("dijit.form.Button")
			->requireModule("dijit.form.DropDownButton")
			->requireModule("dijit.Menu")
			->requireModule("dijit.MenuItem")
			->requireModule("dijit.dijit")
            ->requireModule("dijit.Calendar")
			->requireModule("dojo.data.ItemFileWriteStore")
			->requireModule("dojo.date.locale")
			->requireModule("dijit.Tree")
			->requireModule("dojo.cookie")
			->requireModule("dojox.layout.ContentPane")
		    ->requireModule("dijit.layout.TabContainer")
			->requireModule("dijit.Dialog")
			->requireModule("dijit.form.Form")
			->requireModule("dijit.form.TextBox")
			->requireModule("dijit.form.Button")
			->requireModule("dijit.form.DateTextBox")
			->requireModule("dijit.form.FilteringSelect")
			->requireModule("dojox.grid.DataGrid")
			->requireModule("dojox.grid.EnhancedGrid")
			->requireModule("dojox.grid.enhanced.plugins.Pagination")
			->requireModule("dojox.form.CheckedMultiSelect")
			->requireModule("dojox.encoding.digests.MD5")
			->requireModule("dojo.data.ItemFileWriteStore")
			->requireModule("dojo.data.ItemFileReadStore")
			->requireModule("dojo.date.locale")
			;	
    	
    	
		$this->view->headStyle()->appendStyle('
			@import "'.$this->base_dojo_folder.'/dojox/grid/resources/Grid.css";
			@import "'.$this->base_dojo_folder.'/dojox/grid/resources/claroGrid.css";
			@import "'.$this->base_dojo_folder.'/dojox/form/resources/CheckedMultiSelect.css";
			@import "'.BASE_URL.'/css/admin.css";
		');	
    	

    }
    
    public function componentsAction()
    {
    	if(!Zend_Auth::getInstance()->hasIdentity()) $this->_redirect('index/login');
    	$userInfo = Zend_Auth::getInstance()->getStorage()->read();
        $this->_acl = new Zwei_Admin_Acl($userInfo->user_name);	
    	
    	
    	$Form=new Zwei_Utils_Form();
		$Xml=new Zwei_Admin_Xml();
    	
    	if(isset($Form->p))
    	{
        	if($this->_acl->isUserAllowed($Form->p, "LIST") || $this->_acl->isUserAllowed($Form->p, "EDIT") || $this->_acl->isUserAllowed($Form->p, "ADD")){	
				$Xml->parse(COMPONENTS_ADMIN_PATH."/".$Form->p.".xml");
				$ComponentClass="Zwei_Admin_Components_".Zwei_Utils_String::toClassWord($Xml->elements[0]['TYPE']);
				$View=new $ComponentClass($Form->p, $this->view);
				$content=$View->display();
        	}else{
        		$content="Acceso denegado a módulo";
        	}
			
		}else{
			$content="portada";
		}
		
		if(isset($Form->ajax)){
			$this->_helper->viewRenderer->setNoRender(true);
			echo $content;
		}else{
			$this->view->content = $content;
		}  
    }
    
    
	public function modulesAction()
	{
    	if(!Zend_Auth::getInstance()->hasIdentity()) $this->_redirect('index/login');
    	$userInfo = Zend_Auth::getInstance()->getStorage()->read();
        $this->_acl = new Zwei_Admin_Acl($userInfo->user_name);	
    	
		
	    Zend_Dojo::enableView($this->view);
    
	 	$this->_helper->ContextSwitch
        	->setAutoJsonSerialization(false)
            ->addActionContext('index', 'json')
            ->initContext();   
    
	    $this->_helper->viewRenderer->setNoRender(true);
	    $Modules = new AclModulesModel();
	    $Modules->setApproved();
	    
	    /*$tree=array();
	    foreach($Modules->getTree() as $i=>$v){
			if($this->_acl->isUserAllowed($v, 'LIST')){}		    		    	
	    }*/
		$tree=$Modules->getTree();
	    
	    $treeObj = new Zend_Dojo_Data('id', $tree);
	    $treeObj->setLabel('label');
	    
	    echo Zend_Json::prettyPrint($treeObj->toJson());
	}      
	
    public function loginAction()
    {
    	
    	$this->view->headStyle()->appendStyle('
			@import "'.BASE_URL.'css/admin.css";
		');	
    	
        if(Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_redirect(BASE_URL. 'index');
        }

        $request = $this->getRequest();
        $loginForm = $this->getLoginForm();

        $errorMessage = "";

        if($request->isPost())
        {
            if($loginForm->isValid($request->getPost()))
            {

                $authAdapter = $this->getAuthAdapter();

                $username = $loginForm->getValue('username');
                $password = $loginForm->getValue('password');

                $authAdapter->setIdentity($username)
                            ->setCredential($password);

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);

                if($result->isValid())
                {
   	
                    // Obtenter toda la info de usuario, excepto la password
                    $userInfo = $authAdapter->getResultRowObject(null, 'password');

                    $authSession = new Zend_Session_Namespace('Zend_Auth');
					$authSession->setExpirationSeconds(3600);
                    
                    // El storage por defecto es una session con namespace Zend_Auth
                    $authStorage = $auth->getStorage();
                    $authStorage->write($userInfo);

                    $this->_redirect(BASE_URL.'index');
                }
                else
                {
                    $errorMessage = "Usuario o Password incorrectos.";
                }
            }
        }
        $this->view->errorMessage = $errorMessage;
        $this->view->loginForm = $loginForm;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect(BASE_URL.'index/login');
    }

    /**
     * Gets the adapter for authentication against a database table
     *
     * @return object
     */
    protected function getAuthAdapter()
    {
        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('acl_users')
                    ->setIdentityColumn('user_name')
                    ->setCredentialColumn('password')
                    ->setCredentialTreatment('MD5(?)');
                    
        return $authAdapter;
    }

    /**
     * login form
     *
     * @return object
     */
    protected function getLoginForm()
    {
        $username = new Zend_Dojo_Form_Element_ValidationTextBox('username');
        $username->setLabel('Usuario:')
                ->setRequired(true);

        $password = new Zend_Dojo_Form_Element_PasswordTextBox('password');
        $password->setLabel('Contraseña:')
                ->setRequired(true);

        $submit = new Zend_Form_Element_Submit('login');
        $submit->setLabel('Login');

        $loginForm = new Zend_Dojo_Form();
        $loginForm->setTranslator();
        $loginForm->setAction($this->_request->getBaseUrl().'/index/login/')
        		->setTranslator(new Zend_Translate('array',array("Value is required and can't be empty"=>"Este valor no puede ir vacío"),'es'))
                ->setMethod('post')
                ->addElement($username)
                ->addElement($password)
                ->addElement($submit);

        return $loginForm;
    }
}

